package utils

import (
	"chat/common/msg"
	"encoding/binary"
	"encoding/json"
	"fmt"
	"net"
)

type Transfer struct {
	Conn net.Conn
	Buf  [8064]byte //数组，当做切片使用 传输缓冲
}

func (this *Transfer) ReadPkg() (msg msg.Message, err error) {
	//buf := make([]byte, 8096)
	buf := this.Buf
	conn := this.Conn
	_, err = conn.Read(buf[:4])
	if err != nil {
		fmt.Println("conn.Read header error = ", err)
		return
	}
	fmt.Println("conn.Read buf = ", buf[:4])
	// 数据转换
	var pkgLen uint32
	pkgLen = binary.BigEndian.Uint32(buf[:4])
	// 读取消息
	n, err := conn.Read(buf[:pkgLen])
	if n != int(pkgLen) || err != nil {
		fmt.Println("conn.Read body error = ", err)
		//err = errors.New("conn.Read body error")
		return
	}
	// 反序列化 ---注意 &msg
	err = json.Unmarshal(buf[:pkgLen], &msg)
	if err != nil {
		fmt.Println("json.Unmarshal error = ", err)
		return
	}
	fmt.Println("msg.Data:", msg)
	return
}

func (this *Transfer) WritePkg(data []byte) (err error) {
	// 先发送长度给对方
	var pkgLen uint32
	pkgLen = uint32(len(data))

	binary.BigEndian.PutUint32(this.Buf[0:4], pkgLen)
	con := this.Conn
	n, err := con.Write(this.Buf[:4])
	if n != 4 || err != nil {
		fmt.Println("writePkg pkgLen error = ", err)
		return
	}
	// 发送data本身
	n, err = con.Write(data)
	if n != int(pkgLen) || err != nil {
		fmt.Println("writePkg pkgLen error = ", err)
		return
	}
	return
}
